import axios from 'axios';

import * as actionTypes from './actionTypes';

export const errorMsg = (msg) => ({
    type: actionTypes.ERROR_MSG,
    msg
});

const authSuccess = (user) => ({
    type: actionTypes.AUTH_SUCCESS,
    user
})

export const loginSuccess = (user) => ({
    type: actionTypes.LOGIN_DATA,
    user
})

export const login = ({user, password}) => {
    if (!user || !password) {
		return errorMsg('用户名或密码不能为空');
	}
	return async dispatch =>{
        const res = await axios({
            method: 'post',
            url: '/user/login',
            data: {user, password}
        })
        if (res.status === 200 && res.data.code === 0) {
            dispatch(authSuccess(res.data.data));
        }else{
            dispatch(errorMsg(res.data.msg))
        } 	
	}
}


//async + await 配合使用。 await必须在async内部

export const register = ({user, password, repeatPsw, type}) => {
    const userMsg = {user, password, type};
    if (!user || !password || !type) {
		return errorMsg('用户名或密码不能为空');
	}
	if (password !== repeatPsw) {
		return errorMsg('密码和确认密码不同');
	}
    return async (dispatch) => {
        const res = await axios({
            method: 'post',
            url: '/user/register',
            data: userMsg
        })
        if (res.status === 200 && res.data.code === 0) {
            dispatch(authSuccess({user, password, repeatPsw, type}));
        }else{
            dispatch(errorMsg(res.data.msg))
        } 

    }
}

export const updateInfo = (info) => {
    return (dispatch) => {
        axios({
            method: 'post',
            url: '/user/update',
            data: info
        }).then((res) => {
            console.log(res);
            if (res.status === 200 && res.data.code === 0) {
                dispatch(authSuccess(res.data.data));
            }else{
                dispatch(errorMsg(res.data.msg))
            }         
        }).catch((error) => {
            dispatch(errorMsg('网络请求失败，请重试！'));
        });
    }
}

export const logout = () => ({
    type: actionTypes.LOGOUT
})